#pragma once

#include <iostream>
#include <pthread.h>
#include <time.h>
#include <queue>
#include <unistd.h>
#include "lockGuard.hpp"

using namespace std;
#define NUM 5



template <class T>
class BlockQueue
{
private:
    bool isQueueFull()
    {
        return _capacity == _bq.size();
    }

    bool isQueueEmpty()
    {
        return 0 == _bq.size();
    }

public:
    BlockQueue(int capaicty = NUM)
        :_capacity(capaicty)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_empty,nullptr);
        pthread_cond_init(&_full,nullptr);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_empty);
        pthread_cond_destroy(&_full);
    }

    void Push(const T& in)
    {
        lockGuard lockguard(&_mutex);
        while(isQueueFull())
        {
            pthread_cond_wait(&_full,&_mutex);
        }
        _bq.push(in);
        pthread_cond_signal(&_empty);
    }

    void Pop(T* out)
    {
        lockGuard lockguard(&_mutex);
        while(isQueueEmpty())
        {
            pthread_cond_wait(&_empty,&_mutex);
        }
        *out = _bq.front();
        _bq.pop();
        pthread_cond_signal(&_full);
    }

private:
    queue<T> _bq;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _empty;
    pthread_cond_t _full;
};